package com.yc.ws;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.pojo.Message;
import com.yc.utils.MessageUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/chat",configurator = GetHttpSessionConfig.class)
@Component
public class ChatEndpoint {
    //用来存储每个endpoint对象
    private static Map<String,ChatEndpoint> onLineUsers=new ConcurrentHashMap<>();

    //通过该对象可以发送消息给指定客户端
    private Session session;
    //声明一个HTTP session对象，之前在HTTP session存储了用户名和用户信息
    private HttpSession httpSession;
    @OnOpen
    //连接成功后被调用
    public void onOpen(Session session, EndpointConfig config){
        this.session=session;
        HttpSession httpSession= (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        this.httpSession=httpSession;

        String username= (String) httpSession.getAttribute("user");

        onLineUsers.put(username,this);

        String messsage= MessageUtils.getMessage(true,null,getNames());
        //j进行系统消息的推送
        boradcastAllUsers(messsage);
    }

    private void boradcastAllUsers(String message){
        try{
            Set<String > names=onLineUsers.keySet();
            for (String name:names){
                ChatEndpoint chatEndpoint=onLineUsers.get(name);
                chatEndpoint.session.getBasicRemote().sendText(message);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private Set<String> getNames(){
        return onLineUsers.keySet();
    }
    @OnMessage
    //接收到消息后被调用
    public void onMessage(String message,Session session){
            try{
                ObjectMapper mapper=new ObjectMapper();
                Message mess=mapper.readValue(message, Message.class);
                String toName=mess.getToName();
                String data=mess.getMessage();
                String usenamer= (String) httpSession.getAttribute("user");
                String resultMessage=MessageUtils.getMessage(false,usenamer,data);
                onLineUsers.get(toName).session.getBasicRemote().sendText(resultMessage);
            }catch (Exception e){
                e.printStackTrace();
            }
    }
    @OnClose
    public void onClose(Session session){

    }
}
